// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({
  env: cloud.DYNAMIC_CURRENT_ENV
})
const db = cloud.database()
const _ = db.command
// 云函数入口函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  // 查询访问量及访问人数
  if (event.tag == "selectFangwen") {
    let _updateTime = event._updateTime
    let result = {}
    return await db.collection('fangwencishu').where({
        _updateTime
      }).get()
      .then(res => {
        result.avatar = res.data[0].avatar
        return new Promise((resolve, reject) => {
          db.collection('user').where({
              _updateTime
            }).count()
            .then(res => {
              result.renshu = res.total
              resolve(result)
            })
        })
      })
  }

  // 设置访问次数
  if (event.tag == "fangwencishu") {
    return await db.collection('fangwencishu').where({
        _updateTime: event._updateTime
      }).get()
      .then(res => {
        let result = new Promise((resolve, reject) => {
          if (res.data.length == 1) {
            db.collection('fangwencishu').where({
              _updateTime: event._updateTime
            }).update({
              data: {
                avatar: _.inc(1)
              }
            }).then(() => {
              resolve("在你之前有人访问过了，次数+1")
              
            })
          } else {
            db.collection('fangwencishu').add({
              data: {
                _updateTime: event._updateTime,
                _createTime:db.serverDate(),
                avatar: 1
              }
            }).then(() => {
              resolve("你来的真早，今天第一个来，访问次数+1")
            })
          }
        })
        return result
      }).catch(() => {
        return "错误"
      })

  }

  // return {
  //   event,
  //   openid: wxContext.OPENID,
  //   appid: wxContext.APPID,
  //   unionid: wxContext.UNIONID,
  // }
}